package com.yc.testThread;

import com.yc.baseapi.HandleString;

import java.util.Map;
import java.util.concurrent.*;
import java.util.function.BiPredicate;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;

/**
 * Created with IntelliJ IDEA.
 * description:
 * author: yc
 * date: 2021/2/5 23:19
 */
public class C1 {

    public static void main(String[] args) {
        C1 c1 = new C1();
        c1.m1();
//        c1.m2();
    }


    //测试引用函数
    public void m2() {
        HandleString hs = new HandleString();
        Function<String, String> f2 = hs::m8;
        Consumer<String> f3 = hs::m9;
        Supplier<String> f4 = hs::m10;
//        f2.apply("hello");
//        f3.accept("hello2");
        f4.get();
    }


    /**
     *
     * @param f 函数
     * @param p 参数
     */
    public void m1() {

        HandleString hs = new HandleString();
//        hs.m7();

        Function<String, String> f2 = hs::m8;//用户的代码
        Consumer<String> f3 = hs::m9;//用户的代码
        ItemCallable ic = new ItemCallable(f2, "hello");
        FutureTask ft = new FutureTask(ic);
        Thread it = new Thread(ft);
        it.start();

        boolean flage = false;
        for (int i = 1; i < 10; i++) {
            try {
                ft.get(2, TimeUnit.SECONDS);
                flage = true;
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            } catch (TimeoutException e) {
                System.out.println("-----" + (i*2) + "秒");
                if (flage) {
                    System.out.println("--执行完！---");
                    break;
                }
            }
        }


//        new Callable<Integer>() {
//
//            @Override
//            public Integer call() throws Exception {
//                return null;
//            }
//        };

    }

    class ItemCallable<T> implements Callable<Integer> {
        T param = null;
        Object method = null;
        public ItemCallable(Object f, T t) {
            param = t;
            method = f;
        }

        @Override
        public Integer call() throws Exception {
            if (method instanceof  Function)
                ((Function)method).apply(param);
            if (method instanceof Consumer)
                ((Consumer)method).accept(param);
            return 1;
        }
    }

}
